package com.yrd.common.handler;

public class Looper {
	static ThreadLocal<Looper> local = new ThreadLocal<Looper>();
	volatile boolean alive;
	MessageQueue queue;
	
	private Looper() {
		alive=true;
		queue = new MessageQueue();
	}
	
	public void loop(){
		while(alive){
			Message msg = queue.next();
			if(msg!=null){
				if(msg.type==Message.TYPE_RUNNABLE){
					msg.runnable.run();
				}else if(msg.type==Message.TYPE_CALLABLE){
					msg.future.run();
				}else{
					msg.handle.handleMessage(msg);
				}
			}
		}
	}
	
	public void quit(){
		alive=false;
		try {
			queue.quit();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static Looper myLooper(){
		return local.get();
	}
	public static final void prepare() {
        if (local.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        local.set(new Looper());
    }
}
